package com.qding.park.manager.service.core.biz;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qding.park.common.core.cache.service.CacheServiceFacade;
import com.qding.park.common.core.exceptions.BaseException;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.business.manager.adapterfactory.AdapterProxyCreateFail;
import com.qding.park.common.core.exceptions.business.manager.service.ServiceCoreException;
import com.qding.park.common.core.exceptions.business.payment.PaymentException;
import com.qding.park.common.core.exceptions.system.NetWorkException;
import com.qding.park.common.core.redis.JedisClient;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.OrderNumUtil;
import com.qding.park.manager.adapter.factory.AdapterParkProxyFactory;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.cache.UserCacheInter;
import com.qding.park.manager.payment.PaymentInterfaceServiec;
import com.qding.park.manager.pojo.TbCar;
import com.qding.park.manager.pojo.TbFeetrade;
import com.qding.park.manager.pojo.TbMonthRent;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.TbReserve;
import com.qding.park.manager.pojo.TbUserInfo;
import com.qding.park.manager.pojo.ap.ApMonthFeeOrder;
import com.qding.park.manager.pojo.ap.ApReserveOrder;
import com.qding.park.manager.pojo.enums.MonthRentStatuEnum;
import com.qding.park.manager.pojo.enums.OrderServiceType;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.enums.ParkFeeModelEnum;
import com.qding.park.manager.pojo.enums.RecordStatusEnum;
import com.qding.park.manager.pojo.enums.ReserverStatusEnum;
import com.qding.park.manager.pojo.enums.ReserverTypeEnum;
import com.qding.park.manager.pojo.enums.UserTypeEnum;
import com.qding.park.manager.pojo.noncore.NcMonthRent;
import com.qding.park.manager.pojo.noncore.NcParkInoutInfo;
import com.qding.park.manager.pojo.noncore.NcTempPayInfo;
import com.qding.park.manager.pojo.payment.AbstractResult;
import com.qding.park.manager.pojo.payment.OrderParameter;
import com.qding.park.manager.pojo.payment.ResultCreateorder;
import com.qding.park.manager.service.core.dao.MongodbDao;
import com.qding.park.manager.service.core.mapper.TbCarMapper;
import com.qding.park.manager.service.core.mapper.TbFeetradeMapper;
import com.qding.park.manager.service.core.mapper.TbInoutRecordMapper;
import com.qding.park.manager.service.core.mapper.TbMonthRentMapper;
import com.qding.park.manager.service.core.mapper.TbParkspaceMapper;
import com.qding.park.manager.service.core.mapper.TbReserveMapper;
import com.qding.park.manager.service.core.mapper.TbUserInfoMapper;
import com.qding.park.target.common.adapter.CarAdapter;
import com.qding.park.target.common.adapter.PayFeeAdapter;
import com.qding.park.target.common.adapter.ReserveAdapter;
import com.qding.park.target.common.entity.AdCarInfo;
import com.qding.park.target.common.entity.AdMonthFeeOrder;
import com.qding.park.target.common.entity.AdTempPayOrder;
import com.qding.park.target.common.entity.AdTempPayResult;

/**
 * @ClassName PayFeeBiz
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author Administrator
 * @Date 2016年8月25日 下午6:45:12
 * @version 1.0.0
 */
@Component("payFeeBiz")
public class PayFeeBiz {

    private static final Log _log = LogFactory.getLog(PayFeeBiz.class);
    /**
     * @Field @tbReserveMapper : TODO(预定，临停缴费单)
     */
    @Autowired
    private TbReserveMapper tbReserveMapper;

    /**
     * @Field @tbUserInfoMapper : TODO(用户)
     */
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;

    /**
     * @Field @tbFeetradeMapper : TODO(资金流水)
     */
    @Autowired
    private TbFeetradeMapper tbFeetradeMapper;

    /**
     * @Field @TbParkspaceMapper : TODO(车场)
     */
    @Autowired
    private TbParkspaceMapper tbParkspaceMapper;

    /**
     * @Field @TbMonthRentMapper : TODO(月租单)
     */
    @Autowired
    private TbMonthRentMapper tbMonthRentMapper;

    /**
     * @Field @tbCarMapper : TODO(这里用一句话描述这个类的作用)
     */
    @Autowired
    private TbCarMapper tbCarMapper;
    @Autowired
    private MongodbDao mongodbDao;

    @Autowired
    private AdapterParkProxyFactory adapterParkProxyFactory;

    @Autowired
    private TbInoutRecordMapper tbInoutRecordMapper;

    @Autowired
    private CacheServiceFacade cacheServiceFacade;

    @Autowired
    private InoutcheckBiz inoutcheckBiz;

    @Autowired
    private JedisClient jedisClient;

    @Autowired
    private PaymentInterfaceServiec paymentInterfaceServiec;

    @Autowired
    private ParkCacheInter parkCacheInter;

    @Autowired
    private UserCacheInter userCacheInter;

    /**
     * createReservePayOrder(创建预定订单) @Title: createReservePayOrder @Description: TODO @param @return 设定文件 @return
     * TbReserve 返回类型 @throws
     */
    public TbReserve createReservePayOrder() {

        TbReserve tbReserve = new TbReserve();

        return null;
    }

    // public TbReserve createTeneratPayOrder(String orderId)throws BaseException{
    // String orderStr = jedisClient.hget(CacheKeyThree.TEMPPAY_ORDER_DATA_KEY, orderId);
    //
    // if (StringUtils.isBlank(orderStr)) {
    // throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(), null,
    // ExceptionMessage.createExceptionMessage(
    // ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(), "订单已失效",
    // " orderId=" + orderId));
    // }
    //
    // // 订单
    // TbReserve reserve = SerializeUtils.unSerialize(orderStr, TbReserve.class);
    //
    // int orderType = OrderParameter.OrderTypeEnum.CUSTOMER_PAYMENT_TYPE.getType();
    // int totalPrice = reserve.getDeposit();
    // int orderSource = OrderParameter.OrderSourceEnum.WX.getType();
    // String szCarpassId = reserve.getId();
    // String memberId = reserve.getBjuserId();
    // OrderParameter orderparameter = new OrderParameter();
    // orderparameter.setOrderType(orderType);
    // orderparameter.setTotalPrice(totalPrice);
    // orderparameter.setOrderSource(orderSource);
    // orderparameter.setSzCarpassId(szCarpassId);
    // orderparameter.setMemberId(memberId);
    // orderparameter.setProjectId("77");
    //
    // ResultCreateorder resultCreateorder = paymentInterfaceServiec.createOrder(orderparameter);
    // if (resultCreateorder.getCode() != AbstractResult.ResultCodeEnum.SUCESS.getCode()) {
    // throw new PaymentException(PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getId(), null,
    // ExceptionMessage.createExceptionMessage(PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getDesc(),
    // "创建订单失败:payPlatform:"+resultCreateorder.getMessage(), " orderType=" + orderType + ",totalPrice=" + totalPrice +
    // ",orderSource"
    // + orderSource+",szCarpassId="+szCarpassId+",memberId="+memberId+",orderId"+orderId));
    // }
    //
    // String bjTradeid = resultCreateorder.getOrderId();
    // reserve.setBjOrderId(bjTradeid);
    // reserve.setStatus(ReserverStatusEnum.TEMP_PAY_UNPAYED.getStatus());
    // int num = tbReserveMapper.save(reserve);
    //
    // if (num == 0) {
    // throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_SAVE.getId(), null,
    // ExceptionMessage.createExceptionMessage(
    // ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_SAVE.getDesc(), "失败的保存数据",
    // " orderType=" + orderType + ",totalPrice=" + totalPrice + ",orderSource"
    // + orderSource+",szCarpassId="+szCarpassId+",memberId="+memberId+",orderId"+orderId));
    // }
    //
    // cacheServiceFacade.tempPay_cache_delete(reserve);
    // return reserve;
    // }

    @Transactional(rollbackFor = Throwable.class)
    public TbReserve createTemPayOrder(String orderId) throws BaseException {

        TbReserve reserve = cacheServiceFacade.tempPay_cache_get(orderId);
        if (reserve.getDeposit() == 0) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(), "没有费用产生，请直接出场",
                            " orderId=" + orderId));
        }

        int parkId = reserve.getParkID();
        if (reserve == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(), "订单已失效",
                            " orderId=" + orderId));
        }
        int orderType = OrderParameter.OrderTypeEnum.TEMP_PAY_TYPE.getType();
        if (reserve.getReserverType() == ReserverTypeEnum.GENERATION.getType()) {
            orderType = OrderParameter.OrderTypeEnum.CUSTOMER_PAYMENT_TYPE.getType();
        }

        if (StringUtils.isBlank(reserve.getBjOrderId())) {
            TbParkspace tbParkspace = parkCacheInter.queryParkSpace(parkId);
            int totalPrice = reserve.getDeposit();
            int orderSource = OrderSourceEnum.APP.getType();
            String szCarpassId = reserve.getId();
            String memberId = reserve.getBjuserId();
            OrderParameter orderparameter = new OrderParameter();
            orderparameter.setOrderType(orderType);
            orderparameter.setTotalPrice(totalPrice);
            orderparameter.setOrderSource(orderSource);
            orderparameter.setSzCarpassId(szCarpassId);
            orderparameter.setMemberId(memberId);
            orderparameter.setProjectId(tbParkspace.getBjprojectId());

            ResultCreateorder resultCreateorder = paymentInterfaceServiec.createOrder(orderparameter);
            if (resultCreateorder.getCode() != AbstractResult.ResultCodeEnum.SUCESS.getCode()) {
                throw new PaymentException(PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getId(), null,
                        ExceptionMessage.createExceptionMessage(
                                PaymentException.TypeEnum.EXCEPTION_PAYMENT_FAIL.getDesc(),
                                "创建订单失败:payPlatform:" + resultCreateorder.getMessage(),
                                " orderType=" + orderType + ",totalPrice=" + totalPrice + ",orderSource" + orderSource
                                        + ",szCarpassId=" + szCarpassId + ",memberId=" + memberId + ",orderId"
                                        + orderId));
            }

            String bjTradeid = resultCreateorder.getOrderId();
            reserve.setBjOrderId(bjTradeid);
            reserve.setCreate_date(new Date());
            reserve.setStatus(ReserverStatusEnum.TEMP_PAY_UNPAYED.getStatus());
            reserve.setOrderSource(orderSource);
            int num = tbReserveMapper.save(reserve);
            cacheServiceFacade.tempPay_cache_add(reserve);
        }

        // reserve.setBjOrderId(bjTradeid);
        // reserve.setStatus(ReserverStatusEnum.TEMP_PAY_UNPAYED.getStatus());
        // int num = tbReserveMapper.save(reserve);
        //
        // if (num == 0) {
        // throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_SAVE.getId(), null,
        // ExceptionMessage.createExceptionMessage(
        // ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_SAVE.getDesc(), "失败的保存数据",
        // " orderType=" + orderType + ",totalPrice=" + totalPrice + ",orderSource"
        // + orderSource+",szCarpassId="+szCarpassId+",memberId="+memberId+",orderId"+orderId));
        // _log.info("重复生成订单!!");
        // }

        // cacheServiceFacade.tempPay_cache_delete(reserve);
        // cacheServiceFacade.tempPay_cache_add(reserve);
        return reserve;

    }

    public void tempPayed(TbReserve tbReserve) throws AdapterProxyCreateFail, NetWorkException, AdapterException {
        // 得到车场编号
        int parkId = tbReserve.getParkID();
        int userId = tbReserve.getUserID();
        // 车场订单号
        String parkOrderId = tbReserve.getParkOrderId();
        // 查询车场信息
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);
        String parkCode = tbParkspace.getParkCode();
        int supplierId = tbParkspace.getSupplierId();
        AdTempPayResult apTempPayOrderTemp = new AdTempPayResult();
        apTempPayOrderTemp.setParkCode(parkCode);
        apTempPayOrderTemp.setOrderId(tbReserve.getParkOrderId());
        apTempPayOrderTemp.setRealAmount(tbReserve.getDeposit());
        apTempPayOrderTemp.setPayTime(new Date());
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        adapterProxy.tempPaySuccessNotice(apTempPayOrderTemp);

        tbReserveMapper.tempParkHandled(tbReserve.getId());
    }

    public void teneratPayed(TbReserve tbReserve) throws AdapterProxyCreateFail, NetWorkException, AdapterException {
        // 得到车场编号
        int parkId = tbReserve.getParkID();
        int userId = tbReserve.getUserID();
        // 车场订单号
        String parkOrderId = tbReserve.getParkOrderId();
        // 查询车场信息
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);
        String parkCode = tbParkspace.getParkCode();
        int supplierId = tbParkspace.getSupplierId();
        AdTempPayResult apTempPayOrderTemp = new AdTempPayResult();
        apTempPayOrderTemp.setParkCode(parkCode);
        apTempPayOrderTemp.setOrderId(tbReserve.getParkOrderId());
        apTempPayOrderTemp.setRealAmount(tbReserve.getDeposit());
        apTempPayOrderTemp.setPayTime(new Date());
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        adapterProxy.tempPaySuccessNotice(apTempPayOrderTemp);

        tbReserveMapper.teneratParkHandled(tbReserve.getId());
    }

    public void monthPayedAfter(TbMonthRent tbMonthRent)
            throws AdapterProxyCreateFail, NetWorkException, AdapterException {

        int monthNum = tbMonthRent.getBuyMonths();

        // 得到车场编号
        int parkId = tbMonthRent.getParkID();
        int userId = tbMonthRent.getUserID();
        /******* 下发月卡通知单 ************/
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);
        // 查询供应商信息
        int supplierId = tbParkspace.getSupplierId();
        // 车场提供的车场编号
        String parkCode = tbParkspace.getParkCode();
        String carNum = tbMonthRent.getCarNum();
        // int monthNUm=tbMonthRent.getBuyMonths();
        int amount = tbMonthRent.getCost();
        tbMonthRent.setStatus(MonthRentStatuEnum.PAYED_PARKED.getStatus());
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        AdMonthFeeOrder apMonthFeeOrder = adapterProxy.monthPay(parkCode, carNum, monthNum, amount, new Date(),
                tbMonthRent.getId());
        Date expireDate = apMonthFeeOrder.getExpireDate();
        tbCarMapper.updateExpireDate(parkId, userId, carNum, expireDate);
        // 更新月租订单属性
        tbMonthRentMapper.payedHandled(tbMonthRent);
    }

    /**
     * @Description (创建临停缴费单)
     * @param reserver
     *            临停缴费单
     * @return 临停缴费单号
     * @throws AdapterProxyCreateFail
     * @throws NetWorkException
     * @throws AdapterException
     * @throws ServiceCoreException
     */
    @Transactional(rollbackFor = Throwable.class)
    public void createTempPayment(TbReserve reserver)
            throws AdapterProxyCreateFail, NetWorkException, AdapterException, ServiceCoreException {

        // 查询用户信息
        String bjuserid = reserver.getBjuserId();
        TbUserInfo tbUserInfo = tbUserInfoMapper.queryUserByBjUserId(bjuserid);
        String carNumStrs = tbUserInfo.getCarNum();
        String carNum = reserver.getCarNum();// 车牌
        int parkId = reserver.getParkID();// 车场

        /************ 判段本车牌是否停在本车场 *****************/

        if (!inoutcheckBiz.isPresence(parkId, carNum)) {
            // 车辆没有停在此车场
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getDesc(), "车辆未进场，无法缴费",
                            "车场=" + parkId + " 车牌=" + carNum));
        }
        /********* 判断车辆是否停在本车场 **********/
        // }

        // 查询车场信息
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);

        reserver.setUserID(tbUserInfo.getId());
        reserver.setParkName(tbParkspace.getName());
        int userId = tbUserInfo.getId();
        reserver.setId(OrderNumUtil.getOrderNum(userId, OrderServiceType.TEMP_PAY.getTag()));
        /******* 这里要到线下查询临停缴费单详情 ************/
        int supplierId = tbParkspace.getSupplierId();
        String parkCode = tbParkspace.getParkCode();
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        AdTempPayOrder apTempPayOrder = adapterProxy.createTempPayment(parkCode, carNum,"");

        reserver.setDeposit(apTempPayOrder.getPayValue());
        reserver.setStatus(ReserverStatusEnum.TEMP_PAY_UNPAYED.getStatus());
        reserver.setCheckInTime(apTempPayOrder.getEnterTime());
        reserver.setCheckOutTime(DateUtils.addSecond(reserver.getCheckInTime(), apTempPayOrder.getParkingTime()));
        reserver.setParkOrderId(apTempPayOrder.getOrderId());

        cacheServiceFacade.tempPay_cache_add(reserver);// 将订单信息加入缓存当中
        /******************/

    }

    @Transactional(rollbackFor = Throwable.class)
    public void createTeneratPayment(TbReserve reserver)
            throws AdapterProxyCreateFail, NetWorkException, AdapterException, ServiceCoreException {

        String bjuserid = reserver.getBjuserId();
        TbUserInfo tbUserInfo = tbUserInfoMapper.queryUseByBjuseridType(bjuserid, UserTypeEnum.REGISTER_USER.getType());
        String carNumStrs = tbUserInfo.getCarNum();
        String carNum = reserver.getCarNum();// 车牌

        // 查询车牌进场记录
        NcParkInoutInfo ncParkInoutInfo = mongodbDao.queryIncheckByCarnum(carNum);

        if (ncParkInoutInfo == null || ncParkInoutInfo.getOutTime() != null) {
            // 车辆没有停在此车场
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getDesc(), "车辆未进场，无法缴费",
                            " 车牌=" + carNum));
        }

        int parkId = ncParkInoutInfo.getParkId();

        // 查询车场信息
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);

        reserver.setUserID(tbUserInfo.getId());
        reserver.setParkName(tbParkspace.getName());
        int userId = tbUserInfo.getId();
        reserver.setId(OrderNumUtil.getOrderNum(userId, OrderServiceType.TEMP_PAY.getTag()));
        /******* 这里要到线下查询临停缴费单详情 ************/
        int supplierId = tbParkspace.getSupplierId();
        String parkCode = tbParkspace.getParkCode();
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        AdTempPayOrder apTempPayOrder = adapterProxy.createTempPayment(parkCode, carNum,"");

        reserver.setDeposit(apTempPayOrder.getPayValue());
        reserver.setParkID(parkId);
        reserver.setStatus(ReserverStatusEnum.TEMP_PAY_UNPAYED.getStatus());
        reserver.setCheckInTime(apTempPayOrder.getEnterTime());
        reserver.setCheckOutTime(DateUtils.addSecond(reserver.getCheckInTime(), apTempPayOrder.getParkingTime()));
        reserver.setParkOrderId(apTempPayOrder.getOrderId());
        reserver.setParkSerial(apTempPayOrder.getParkingSerial());
        /******************/
        _log.info("创建　了代缴费单:" + reserver.getId());

        /***** 缓存订单信息 **********/
        cacheServiceFacade.tempPay_cache_add(reserver);
        /***** 缓存订单信息 **********/

    }

    // /**
    // * createTeneratPayment(代缴费单)
    // * TODO(这里描述这个方法适用条件 – 可选)
    // * TODO(这里描述这个方法的执行流程 – 可选)
    // * TODO(这里描述这个方法的使用方法 – 可选)
    // * TODO(这里描述这个方法的注意事项 – 可选)
    // *
    // * @Title: createTeneratPayment
    // * @Description: TODO
    // * @param @param reserver
    // * @param @return
    // * @param @throws ServiceCoreException
    // * @param @throws AdapterProxyCreateFail
    // * @param @throws NetWorkException
    // * @param @throws AdapterException 设定文件
    // * @return String 返回类型
    // * @throws
    // */
    // @Transactional(rollbackFor=Exception.class)
    // public String createTeneratPayment(TbReserve reserver) throws
    // ServiceCoreException, AdapterProxyCreateFail, NetWorkException,
    // AdapterException{
    // //查询用户信息
    // String bjuserid = reserver.getBjuserId();
    // TbUserInfo tbUserInfo = tbUserInfoMapper.queryUserByBjUserId(bjuserid);
    // String carNumStrs=tbUserInfo.getCarNum();
    // String carNum=reserver.getCarNum();//车牌
    //// int parkId=reserver.getParkID();//车场
    //
    // //查询车牌进场记录
    // NcParkInInfo ncParkInInfo= mongodbCoreDao.queryIncheckByCarnum(carNum);
    //
    // if(ncParkInInfo==null){
    // //车辆没有停在此车场
    // throw new
    // ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getId(),
    // null,
    // ExceptionMessage.createExceptionMessage(
    // ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getDesc(),
    // "车辆未进场，无法缴费",
    // " 车牌=" + carNum));
    // }
    //
    // TbParkspace
    // parkSpace=TbParkspaceMapper.queryParkInfoByCodeSupplier(ncParkInInfo.getParkCode(),
    // Integer.valueOf(ncParkInInfo.getSupplyID()));
    // int parkId=parkSpace.getId();
    //
    //// /************判段本车牌是否停在本车场*****************/
    //// int temp=tbInoutRecordMapper.inByCarnumParkid(parkId,carNum);
    //// if(temp==0){
    //// //车辆没有停在此车场
    //// throw new
    // ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getId(),
    // null,
    //// ExceptionMessage.createExceptionMessage(
    //// ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getDesc(),
    // "车辆未进场，无法缴费",
    //// "车场=" + parkId + " 车牌=" + carNum));
    //// }
    //// /*********判断车辆是否停在本车场**********/
    //// }
    //
    // //查询车场信息
    // TbParkspace tbParkspace=TbParkspaceMapper.queryParkInfoByParkId(parkId);
    //
    // reserver.setUserID(tbUserInfo.getId());
    // reserver.setParkName(tbParkspace.getName());
    // int userId=tbUserInfo.getId();
    // reserver.setId(OrderNumUtil.getOrderNum(userId));
    // /*******这里要到线下查询临停缴费单详情************/
    // int supplierId = tbParkspace.getSupplierId();
    // String parkCode=tbParkspace.getParkCode();
    // AdapterProxy adapterProxy =
    // adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
    // ApTempPayOrder
    // apTempPayOrder=adapterProxy.getPayFeeAdapter().createTempPayment(parkCode,carNum);
    //
    // reserver.setDeposit(apTempPayOrder.getPayValue());
    // reserver.setParkID(parkId);
    //// reserver.setReserverType(ReserverTypeEnum.GENERATION.getType());
    // reserver.setStatus(ReserverStatusEnum.TEMP_PAY_UNPAYED.getStatus());
    // reserver.setCheckInTime(apTempPayOrder.getEnterTime());
    // reserver.setCheckOutTime(DateUtils.addSecond(reserver.getCheckInTime(),
    // apTempPayOrder.getParkingTime()));
    // reserver.setParkOrderId(apTempPayOrder.getOrderId());
    // /******************/
    //
    // int num=tbReserveMapper.save(reserver);
    //
    // return reserver.getId();
    // }

    /**
     * @Description (创建月租续费单)
     * @param tbMonthRent
     * @return
     * @throws AdapterProxyCreateFail
     * @throws NetWorkException
     * @throws AdapterException
     */
    @Transactional(rollbackFor = Throwable.class)
    public void createMonthRentPay(TbMonthRent tbMonthRent)
            throws ServiceCoreException, AdapterProxyCreateFail, AdapterException, NetWorkException {

        // 查询用户id
        String bjuserid = tbMonthRent.getBjuserid();
        TbUserInfo tbUserInfo = tbUserInfoMapper.queryUserByBjUserId(bjuserid);

        if (tbUserInfo == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_USER.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_USER.getDesc(), "", "bjuserid=" + bjuserid));
        }

        int userId = tbUserInfo.getId();
        tbMonthRent.setUserID(tbUserInfo.getId());

        // 查询车场名
        int parkId = tbMonthRent.getParkID();
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);
        if (tbParkspace == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_PARK.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_PARK.getDesc(), "没有此用户",
                            "parkId=" + parkId));
        }

        tbMonthRent.setParkName(tbParkspace.getName());

        tbMonthRent.setStatus(MonthRentStatuEnum.INVALID.getStatus());

        TbCar tbCar = tbCarMapper.queryCarOfParkByParkIdUserIdCarNum(parkId, userId, tbMonthRent.getCarNum());
        if (tbCar == null || tbCar.getCardExpiration() == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_MONTHCARD_NOTPAY.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_MONTHCARD_NOTPAY.getDesc(), "首次缴费请至物业中心缴纳",
                            "车牌=" + tbMonthRent.getCarNum() + ",订单号=" + tbMonthRent.getId()));
        }

        /******* 查询月卡基本状态信息 ***********/
        // 查询供应商信息
        int supplierId = tbParkspace.getSupplierId();
        // 车场提供的车场编号
        String parkCode = tbParkspace.getParkCode();
        String carNum = tbMonthRent.getCarNum();
        CarAdapter adapterProxy = adapterParkProxyFactory.getCarAdapter(String.valueOf(supplierId));
        AdCarInfo apUserCarInfo = adapterProxy.getMonthCardInfo(parkCode, carNum);
        /******************/
        // if (!"1".equals(apUserCarInfo.getIsCharge())) {
        if (!apUserCarInfo.isCharge()) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_MONTHCARD_NOTPAY.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_MONTHCARD_NOTPAY.getDesc(),
                            "此车牌不能冲值/" + apUserCarInfo.getMsg(), "车牌=" + carNum));
        }

        Date today = DateUtils.dateFormat(new Date());
        if (apUserCarInfo.getExpireDate() == null || (apUserCarInfo.getExpireDate().getTime() < today.getTime())
                || tbCar.getCardExpiration().getTime() < today.getTime()) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_MONTHCARD_NOTPAY.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_MONTHCARD_NOTPAY.getDesc(), "您的月牌已过期，请联络物业管理中心处理",
                            "车牌=" + carNum));
        }
        // 查询即将到期时间

        tbMonthRent.setOldExpiredate(apUserCarInfo.getExpireDate());
        tbMonthRent.setExpiredate(apUserCarInfo.getExpireDate());
        tbMonthRent.setId(OrderNumUtil.getOrderNum(userId, OrderServiceType.MONTHRENT.getTag()));
        tbMonthRent.setBuyMonths(1);
        tbMonthRent.setCost(apUserCarInfo.getMonthFee());
        tbMonthRent.setCreate_date(new Date());
        tbMonthRent.setParkOrderId(tbMonthRent.getId());
        tbMonthRent.setStatus(MonthRentStatuEnum.NOT_PAY.getStatus());

        cacheServiceFacade.monthrentPay_cache_add(tbMonthRent);// 将订单信息加入缓存当中
        _log.info("创建了月租续费单:" + tbMonthRent.getId() + ",status=" + tbMonthRent.getStatus());

    }

    /**
     * @Description (临停缴费支付成功通知) @Transactional
     * @param orderId
     * @param realPayAmount
     *            实收金额
     * @return
     * @throws AdapterProxyCreateFail
     * @throws NetWorkException
     * @throws AdapterException
     */
    @Transactional(rollbackFor = Throwable.class)
    public int teneratPaySuccessNotice(String orderId, int realPayAmount)
            throws AdapterProxyCreateFail, NetWorkException, AdapterException {
        TbReserve tbReserve = tbReserveMapper.queryReservesInfoById(orderId);

        // 得到车场编号
        int parkId = tbReserve.getParkID();
        int userId = tbReserve.getUserID();

        TbFeetrade tbFeetrade = new TbFeetrade();
        tbFeetrade.setId(OrderNumUtil.getOrderNum(userId, OrderServiceType.FEETRADE.getTag()));
        tbFeetrade.setUserID(tbReserve.getUserID());
        tbFeetrade.setParkID(tbReserve.getParkID());
        tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.CAPITALFLOW_TEMP_PAY.getType());
        tbFeetrade.setFeeCost(realPayAmount);// 实收金额
        tbFeetrade.setBusinessID(tbReserve.getId());
        tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
        tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());

        // 保存流水
        int num1 = tbFeetradeMapper.save(tbFeetrade);
        String tradeID = tbFeetrade.getId();

        tbReserve.setRealPayDeposit(realPayAmount);
        tbReserve.setTradeid(tradeID);
        tbReserve.setStatus(ReserverStatusEnum.TEMP_PAY_PAYED.getStatus());
        // 更新订单状态
        int num = tbReserveMapper.teneratPaySuccess(tbReserve);
       
        /**********保存mongodb***************************/
        NcTempPayInfo ncTempPayInfo = new NcTempPayInfo();
        ncTempPayInfo.setBjOrderId(tbReserve.getBjOrderId());
        ncTempPayInfo.setCarNum(tbReserve.getCarNum());
        ncTempPayInfo.setCreate_date(tbReserve.getCreate_date());
        ncTempPayInfo.setFeeMoney(tbReserve.getRealPayDeposit());
        ncTempPayInfo.setShouldFeeMoney(tbReserve.getDeposit());
        ncTempPayInfo.setParkId(tbReserve.getParkID());
        ncTempPayInfo.setPayOrderID(tbReserve.getId());
        ncTempPayInfo.setOrderId(tbReserve.getParkOrderId());
        String bjuserid = userCacheInter.userId2bjuserId(String.valueOf(tbReserve.getUserID()));
        String tel = userCacheInter.userId2tel(String.valueOf(tbReserve.getUserID()));
        ncTempPayInfo.setTel(tel);
        ncTempPayInfo.setUserId(tbReserve.getUserID());
        ncTempPayInfo.setOrderSource(tbReserve.getOrderSource());
        mongodbDao.saveNcTempPayInfo(ncTempPayInfo);
        /*******************保存mongodb*********************************/
        // 得到车场编号
        String parkOrderId = tbReserve.getParkOrderId();
        // 查询车场信息
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);
        String parkCode = tbParkspace.getParkCode();
        int supplierId = tbParkspace.getSupplierId();
        AdTempPayResult apTempPayOrderTemp = new AdTempPayResult();
        apTempPayOrderTemp.setParkCode(parkCode);
        apTempPayOrderTemp.setOrderId(tbReserve.getParkOrderId());
        apTempPayOrderTemp.setRealAmount(tbReserve.getDeposit());
        apTempPayOrderTemp.setPayTime(new Date());
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        adapterProxy.tempPaySuccessNotice(apTempPayOrderTemp);
        tbReserveMapper.teneratParkHandled(tbReserve.getId());

        return num;
    }

    /**
     * reserverPaySuccessNotice(预定押金支付成功通知) @Title: reserverPaySuccessNotice @Description: TODO @param @param
     * orderId @param realPayAmount 实收金额 @param @return 设定文件 @return int 返回类型 @throws
     */
    @Transactional(rollbackFor = Throwable.class)
    public int reserverPaySuccessNotice(String orderId, int realPayAmount) throws BaseException {
        TbReserve tbReserve = tbReserveMapper.queryReservesInfoById(orderId);

        // 得到车场编号
        int parkId = tbReserve.getParkID();
        int userId = tbReserve.getUserID();
        // 车场订单号
        String parkOrderId = tbReserve.getParkOrderId();

        TbFeetrade tbFeetrade = new TbFeetrade();
        tbFeetrade.setId(OrderNumUtil.getOrderNum(userId, OrderServiceType.FEETRADE.getTag()));
        tbFeetrade.setUserID(tbReserve.getUserID());
        tbFeetrade.setParkID(tbReserve.getParkID());
        tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.CAPITALFLOW_FEETYPE.getType());
        tbFeetrade.setFeeCost(realPayAmount >= 0 ? realPayAmount : tbReserve.getDeposit());
        tbFeetrade.setBusinessID(tbReserve.getId());
        tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
        tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
        // // 保存流水
        String tradeID = tbFeetrade.getId();
        tbReserve.setTradeid(tradeID);
        tbReserve.setStatus(ReserverStatusEnum.RESERVER_PAYED_SUCCESS.getStatus());
        tbReserve.setRealPayDeposit(realPayAmount >= 0 ? realPayAmount : tbReserve.getDeposit());
        // 更新订单状态
        int num = tbReserveMapper.reservePaysuccess(tbReserve);
        if (num == 0) {
            _log.error("无效数据更新::" + "orderId=" + orderId + ",realPayAmount=" + realPayAmount);
        } else {
            // 保存流水
            int num1 = tbFeetradeMapper.save(tbFeetrade);
//            // 通知进行下一步操作
//            cacheServiceFacade.reserve_payed_queue_push(tbReserve);
//            // 加入监控
//            cacheServiceFacade.reserve_monitor_add(tbReserve);
        }
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(tbReserve.getParkID());
        Date now = new Date();
        Date endTime = tbReserve.getEndTime();
        if (now.getTime() > endTime.getTime()) {
            // 已经超时 支付成功下发失败 退款
            tbReserve.setStatus(ReserverStatusEnum.RESERVER_ISSUED_PARKFail.getStatus());
            // 支付成功超时
            int num1 = tbReserveMapper.timeout_payed(tbReserve);
            if (num1 == 0) {
                return 0;
            }
            String carpassId = tbReserve.getBjOrderId();
            paymentInterfaceServiec.refundOrder(carpassId);
        } else {
            tbReserve.setStatus(ReserverStatusEnum.RESERVER_ISSUED_PARKSUCCESS.getStatus());
            // 没有超时
            int num2 = tbReserveMapper.reservePayedHandle(tbReserve);
            if (num2 == 0) {
                return 0;
            }
            /**** 下发预定单 ********/
            ReserveAdapter adapterProxy = adapterParkProxyFactory
                    .getReserveAdapter(String.valueOf(tbParkspace.getSupplierId()));
            ApReserveOrder apReserveOrder = new ApReserveOrder();
            apReserveOrder.setParkId(tbParkspace.getParkCode());
            apReserveOrder.setCarNum(tbReserve.getCarNum());
            apReserveOrder.setStartTime(tbReserve.getStartTime());
            apReserveOrder.setEndTime(tbReserve.getEndTime());
            apReserveOrder.setOrderId(tbReserve.getParkOrderId());
            adapterProxy.reserveParkSpace(apReserveOrder);
            /**** 下发预定单 ********/
        }

        return num;
    }

    /**
     * @Description (临停缴费支付成功通知) @Transactional
     * @param orderId
     * @return
     * @throws AdapterProxyCreateFail
     * @throws NetWorkException
     * @throws AdapterException
     */
    @Transactional(rollbackFor = Throwable.class)
    public int tempPaySuccessNotice(String orderId, int realPayAmount)
            throws AdapterProxyCreateFail, NetWorkException, AdapterException {
        TbReserve tbReserve = tbReserveMapper.queryReservesInfoById(orderId);

        // 得到车场编号
        int parkId = tbReserve.getParkID();
        int userId = tbReserve.getUserID();
        // 车场订单号
        String parkOrderId = tbReserve.getParkOrderId();
        // 查询车场信息
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);

        /******* 线下操作* 下发通知 ***********/
        // 查询供应商信息
        int supplierId = tbParkspace.getSupplierId();
        // 车场提供的车场编号
        String parkCode = tbParkspace.getParkCode();
        String carNum = tbReserve.getCarNum();
        /******************/

        TbFeetrade tbFeetrade = new TbFeetrade();
        tbFeetrade.setId(OrderNumUtil.getOrderNum(userId, OrderServiceType.FEETRADE.getTag()));
        tbFeetrade.setUserID(tbReserve.getUserID());
        tbFeetrade.setParkID(tbReserve.getParkID());
        tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.CAPITALFLOW_TEMP_PAY.getType());
        tbFeetrade.setFeeCost(realPayAmount);// 实付金额
        tbFeetrade.setBusinessID(tbReserve.getId());
        tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
        tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
        // 保存流水
        int num1 = tbFeetradeMapper.save(tbFeetrade);
        String tradeID = tbFeetrade.getId();
        // 更新订单状态
        tbReserve.setStatus(ReserverStatusEnum.TEMP_PAY_PAYED.getStatus());
        tbReserve.setTradeid(tradeID);
        tbReserve.setRealPayDeposit(realPayAmount);
        int num = tbReserveMapper.tempPaySuccess(tbReserve);
        
        
        /************mongodb**************************/
        NcTempPayInfo ncTempPayInfo = new NcTempPayInfo();
        ncTempPayInfo.setBjOrderId(tbReserve.getBjOrderId());
        ncTempPayInfo.setCarNum(tbReserve.getCarNum());
        ncTempPayInfo.setCreate_date(tbReserve.getCreate_date());
        ncTempPayInfo.setFeeMoney(tbReserve.getRealPayDeposit());
        ncTempPayInfo.setShouldFeeMoney(tbReserve.getDeposit());
        ncTempPayInfo.setParkId(tbReserve.getParkID());
        ncTempPayInfo.setPayOrderID(tbReserve.getId());
        ncTempPayInfo.setOrderId(tbReserve.getParkOrderId());
        String bjuserid = userCacheInter.userId2bjuserId(String.valueOf(tbReserve.getUserID()));
        String tel = userCacheInter.userId2tel(String.valueOf(tbReserve.getUserID()));
        ncTempPayInfo.setTel(tel);
        ncTempPayInfo.setUserId(tbReserve.getUserID());
        ncTempPayInfo.setOrderSource(tbReserve.getOrderSource());
        mongodbDao.saveNcTempPayInfo(ncTempPayInfo);
        /************mongodb**************************/
        
        /******下发车场指令**************/
        
        AdTempPayResult apTempPayOrderTemp = new AdTempPayResult();
        apTempPayOrderTemp.setParkCode(parkCode);
        apTempPayOrderTemp.setOrderId(tbReserve.getParkOrderId());
        apTempPayOrderTemp.setRealAmount(tbReserve.getDeposit());
        apTempPayOrderTemp.setPayTime(new Date());
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        adapterProxy.tempPaySuccessNotice(apTempPayOrderTemp);
        
        tbReserveMapper.tempParkHandled(tbReserve.getId());
        return num;
    }

    /**
     * tempPayFailNotice(临停缴费失败)
     *
     * @Title: tempPayFailNotice @Description: TODO @param @param orderId 设定文件 @return void 返回类型 @throws
     */
    public void tempPayFailNotice(String orderId) throws BaseException {
        // 支付失败
        int num = tbReserveMapper.tempPayFail(orderId, ReserverStatusEnum.TEMP_PAY_PAYFAIL.getStatus());

        if (num == 0) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_UPDATE.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_UPDATE.getDesc(), "无效的订单-tempPayFailNotice",
                            "orderId=" + orderId));
        }
    }

    public void monthPayFailNotice(String orderId) throws BaseException {
        int num = tbMonthRentMapper.payFail(orderId, MonthRentStatuEnum.FAIL_PAY.getStatus());
        if (num == 0) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_UPDATE.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_UPDATE.getDesc(), "无效的订单-tempPayFailNotice",
                            "orderId=" + orderId));
        }
    }

    // /**
    // * @Description (月租续费支付成功通知)
    // * @param orderId
    // * @return
    // * @throws AdapterProxyCreateFail
    // * @throws NetWorkException
    // * @throws AdapterException
    // */
    // @Transactional(rollbackFor=Throwable.class)
    // public int monthPaySuccessNotice(String orderId,int monthNum) throws
    // AdapterProxyCreateFail, NetWorkException, AdapterException{
    //
    //
    // TbMonthRent tbMonthRent=tbMonthRentMapper.queryMonthRentById(orderId);
    //
    //
    // //得到车场编号
    // int parkId=tbMonthRent.getParkID();
    // int userId=tbMonthRent.getUserID();
    // /*******下发月卡通知单************/
    // TbParkspace tbParkspace=TbParkspaceMapper.queryParkInfoByParkId(parkId);
    // //查询供应商信息
    // int supplierId = tbParkspace.getSupplierId();
    // //车场提供的车场编号
    // String parkCode=tbParkspace.getParkCode();
    // String carNum=tbMonthRent.getCarNum();
    //// int monthNUm=tbMonthRent.getBuyMonths();
    // int amount=tbMonthRent.getCost();
    // AdapterProxy adapterProxy =
    // adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
    // ApMonthFeeOrder apMonthFeeOrder=adapterProxy.getPayFeeAdapter().monthPay(
    // parkCode,carNum,monthNum,amount,new Date(),String.valueOf(orderId));
    // Date expireDate=apMonthFeeOrder.getExpireDate();
    // /******************/
    //
    // TbFeetrade tbFeetrade=new TbFeetrade();
    // tbFeetrade.setId(OrderNumUtil.getOrderNum(userId));
    // tbFeetrade.setUserID(tbMonthRent.getUserID());
    // tbFeetrade.setParkID(tbMonthRent.getParkID());
    // tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.CAPITALFLOW_MONTH_PAY.getType());
    // tbFeetrade.setFeeCost(tbMonthRent.getCost());
    // tbFeetrade.setBusinessID(tbMonthRent.getId());
    // tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
    // tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
    // tbFeetradeMapper.save(tbFeetrade);
    // String tradeID=tbFeetrade.getId();
    //
    // //更新车辆到期时间
    // tbCarMapper.updateExpireDate(parkId,userId,carNum,expireDate);
    //
    // //更新用户的最近到期时间
    //// tbUserInfoMapper.updateExpiredTime(tbMonthRent.getUserID(),expireDate);
    // //更新订单状态
    // int num=tbMonthRentMapper.updatePaySuccessByid(orderId,
    // TbMonthRent.StatusEnum.EFFICIENCY.getStatus(),tradeID,expireDate);
    //
    //
    // return num;
    // }

    /**
     * @Description (月租续费支付成功通知)
     * @param orderId
     * @param realPayAmount
     *            实付金额
     * @return
     * @throws AdapterProxyCreateFail
     * @throws NetWorkException
     * @throws AdapterException
     *             将异步改为同步
     */
    @Transactional(rollbackFor = Throwable.class)
    public int monthPaySuccessNotice(String orderId, int realPayAmount)
            throws AdapterProxyCreateFail, NetWorkException, AdapterException {

        TbMonthRent tbMonthRent = tbMonthRentMapper.queryMonthRentById(orderId);
        int monthNum = tbMonthRent.getBuyMonths();

        // 得到车场编号
        int parkId = tbMonthRent.getParkID();
        int userId = tbMonthRent.getUserID();

        TbFeetrade tbFeetrade = new TbFeetrade();
        tbFeetrade.setId(OrderNumUtil.getOrderNum(userId, OrderServiceType.FEETRADE.getTag()));
        tbFeetrade.setUserID(tbMonthRent.getUserID());
        tbFeetrade.setParkID(tbMonthRent.getParkID());
        tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.CAPITALFLOW_MONTH_PAY.getType());
        tbFeetrade.setFeeCost(realPayAmount);// 实付金额
        tbFeetrade.setBusinessID(tbMonthRent.getId());
        tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
        tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
        tbFeetradeMapper.save(tbFeetrade);
        String tradeID = tbFeetrade.getId();

        tbMonthRent.setStatus(MonthRentStatuEnum.EFFICIENCY_ANDPAY.getStatus());
        tbMonthRent.setTradeID(tradeID);
        tbMonthRent.setRealPayCost(realPayAmount);
        int num = tbMonthRentMapper.paySuccess(tbMonthRent);

        tbMonthRent.setParkOrderId(orderId);
        // cacheServiceFacade.monthRentPay_payed(tbMonthRent);

        /********* 记录mongodb数据 **************/
        // String bjuserid = userCacheInter.userId2bjuserId(String.valueOf(tbMonthRent.getUserID()));
        String bjuserid = tbMonthRent.getBjuserid();
        String tel = userCacheInter.userId2tel(String.valueOf(tbMonthRent.getUserID()));
        TbParkspace parkspace = parkCacheInter.queryParkSpace(tbMonthRent.getParkID());
        int supplierId = parkspace.getSupplierId();
        NcMonthRent ncMonthRent = new NcMonthRent();
        ncMonthRent.setAddFeeMode(ParkFeeModelEnum.APP.getType());
        ncMonthRent.setBjOrderId(tbMonthRent.getBjOrderId());
        ncMonthRent.setBjuserid(bjuserid);
        ncMonthRent.setBuyMonths(tbMonthRent.getBuyMonths());
        ncMonthRent.setCarNum(tbMonthRent.getCarNum());
        ncMonthRent.setCreate_date(new Date());
        ncMonthRent.setMonthlyEndTime(tbMonthRent.getExpiredate());
        ncMonthRent.setMonthlyStartTime(tbMonthRent.getOldExpiredate());
        ncMonthRent.setOrderSource(tbMonthRent.getOrderSource());
        ncMonthRent.setParkID(tbMonthRent.getParkID());
        ncMonthRent.setParkName(tbMonthRent.getParkName());
        ncMonthRent.setParkPayId(tbMonthRent.getParkOrderId());
        ncMonthRent.setPay_channel(TbFeetrade.ChannelEnum.CAPITALFLOW_LINE.getType());
        ncMonthRent.setPaymentAmount(tbMonthRent.getRealPayCost());
        ncMonthRent.setPayOrderID(tbMonthRent.getId());
        ncMonthRent.setRechargeDate(tbMonthRent.getCreate_date());
        ncMonthRent.setShouldPaymentAmount(tbMonthRent.getCost());
        ncMonthRent.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
        ncMonthRent.setTradeID(tbMonthRent.getTradeID());
        ncMonthRent.setUpdate_date(new Date());
        ncMonthRent.setUserId(tbMonthRent.getUserID());
        ncMonthRent.setMonthlyBuyFee(tbMonthRent.getCost());
        ncMonthRent.setSupplyID(String.valueOf(supplierId));
        ncMonthRent.setTel(tel);
        mongodbDao.saveNcMonthRent(ncMonthRent);
        /***********************/

        /******* 下发月卡通知单 ************/
        // 查询供应商信息
        // 车场提供的车场编号
        String parkCode = parkspace.getParkCode();
        String carNum = tbMonthRent.getCarNum();
        // int monthNUm=tbMonthRent.getBuyMonths();
        int amount = tbMonthRent.getCost();
        tbMonthRent.setStatus(MonthRentStatuEnum.PAYED_PARKED.getStatus());
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        AdMonthFeeOrder apMonthFeeOrder = adapterProxy.monthPay(parkCode, carNum, monthNum, amount, new Date(),
                tbMonthRent.getId());
        Date expireDate = apMonthFeeOrder.getExpireDate();
        tbCarMapper.updateExpireDate(parkId, userId, carNum, expireDate);
        // 更新月租订单属性
        tbMonthRentMapper.payedHandled(tbMonthRent);
        return num;
    }

    /**
     * @Description (计算月租费用)
     * @param tbRent
     * @throws ServiceCoreException
     * @throws AdapterProxyCreateFail
     * @throws NetWorkException
     * @throws AdapterException
     *             String orderStr = jedisClient.hget(CacheKeyThree.TEMPPAY_ORDER_DATA_KEY, orderId); if
     *             (StringUtils.isBlank(orderStr)) { throw new ServiceCoreException(ServiceCoreException.TypeEnum.
     *             EXCEPTION_NO_DATA_INVALID.getId(), null, ExceptionMessage.createExceptionMessage(
     *             ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID. getDesc(), "订单已失效", " orderId=" + orderId));
     *             } // 订单 TbReserve reserve = SerializeUtils.unSerialize(orderStr, TbReserve.class);
     */
    public TbMonthRent calMonthFee(TbMonthRent tbRent)
            throws ServiceCoreException, AdapterProxyCreateFail, NetWorkException, AdapterException {
        String orderId = tbRent.getId();
        int monthNum = tbRent.getBuyMonths();
        // String carNum=tbRent.getCarNum();
        // TbMonthRent tbMonthRent = tbMonthRentMapper.queryMonthRentById(orderId);
        TbMonthRent tbMonthRent = cacheServiceFacade.monthrentPay_cache_query(orderId);

        if (tbMonthRent == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(), "订单已失效",
                            " orderId=" + orderId));
        }

        int parkId = tbMonthRent.getParkID();
        String carNum = tbMonthRent.getCarNum();
        TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(parkId);
        if (tbParkspace == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_PARK.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_PARK.getDesc(), "", "parkId=" + parkId));
        }

        /******* 这里要到线下查询临停缴费单详情 ************/
        int supplierId = tbParkspace.getSupplierId();
        String parkCode = tbParkspace.getParkCode();
        PayFeeAdapter adapterProxy = adapterParkProxyFactory.getPayFeeAdapter(String.valueOf(supplierId));
        AdMonthFeeOrder apMonthFeeOrder = adapterProxy.calMonthFee(parkCode, monthNum, carNum);
        /******************/
        int cost = apMonthFeeOrder.getTotalFee();

        tbMonthRent.setCost(cost);
        tbMonthRent.setBuyMonths(monthNum);
        tbMonthRent.setExpiredate(apMonthFeeOrder.getExpireDate());
        tbMonthRent.setUpdate_date(new Date());

        // // 更新数据库中邀请单 中的月数和金额数
        // tbMonthRentMapper.updateCostMonthById(orderId, cost, monthNum, tbRent.getExpiredate());
        cacheServiceFacade.monthrentPay_cache_add(tbMonthRent);
        return tbMonthRent;

    }

    @Transactional(rollbackFor = Throwable.class)
    public void monthRentpayedIssuedFailRollBack(TbMonthRent tbMonthRent) {
        // 更新月租订单属性
        tbMonthRent.setStatus(MonthRentStatuEnum.PAYED_PARKFAIL.getStatus());
        tbMonthRentMapper.issuedFailRollBack(tbMonthRent);

        /**** *此处要调用北京接口 ********/
        // 退款押金
        TbFeetrade tbFeetrade = new TbFeetrade();
        tbFeetrade.setId(OrderNumUtil.getOrderNum(tbMonthRent.getUserID(), OrderServiceType.FEETRADE.getTag()));
        tbFeetrade.setUserID(tbMonthRent.getUserID());
        tbFeetrade.setParkID(tbMonthRent.getParkID());
        tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.REFUND_PAY.getType());
        tbFeetrade.setFeeCost(tbMonthRent.getRealPayCost());
        tbFeetrade.setBusinessID(tbMonthRent.getId());
        tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
        tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
        tbFeetradeMapper.save(tbFeetrade);
        /**** 调用北京接口 *****/
        // 没有超时 退还押金
        paymentInterfaceServiec.refundOrder(tbMonthRent.getBjOrderId());
        /**** 调用北京接口 *****/
    }

    @Transactional(rollbackFor = Throwable.class)
    public void reserverPayFailNotice(String orderId) throws BaseException {
        TbReserve tbReserve = tbReserveMapper.queryReservesInfoById(orderId);
        if (tbReserve == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "无效的订单",
                            "orderId=" + orderId));
        }
        tbReserve.setStatus(ReserverStatusEnum.RESERVER_PAYED_FAIL.getStatus());
        tbReserveMapper.reserverPayFail(tbReserve);
    }

    @Transactional(rollbackFor = Throwable.class)
    public void tempIssuedFailRollBack(TbReserve tbReserve) {
        tbReserve.setStatus(ReserverStatusEnum.TEMP_PAY_PARK_FAIL.getStatus());
        tbReserveMapper.tempIssuedFailRollBack(tbReserve);

        /**** *此处要调用北京接口 ********/
        // 退款押金
        TbFeetrade tbFeetrade = new TbFeetrade();
        tbFeetrade.setId(OrderNumUtil.getOrderNum(tbReserve.getUserID(), OrderServiceType.FEETRADE.getTag()));
        tbFeetrade.setUserID(tbReserve.getUserID());
        tbFeetrade.setParkID(tbReserve.getParkID());
        tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.REFUND_PAY.getType());
        tbFeetrade.setFeeCost(tbReserve.getRealPayDeposit());
        tbFeetrade.setBusinessID(tbReserve.getId());
        tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_ONLINE.getType());
        tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
        tbFeetradeMapper.save(tbFeetrade);
        /**** 调用北京接口 *****/
        // 没有超时 退还押金
        paymentInterfaceServiec.refundOrder(tbReserve.getBjOrderId());
        /**** 调用北京接口 *****/
    }
}
